<template>
	<view class="page_body">
		<!-- 状态栏高度 设置背景色 占位状态栏-->
		<view class="ztl"
			:style="{'height':statusBarHeight}"></view>
		<!-- 占位盒子导航栏 -->
		<view class=""
			:style="{'height': hieght}"></view>
		<!-- 导航栏 -->
		<navBar bg-color="#FFF">
			<image :slot="'left'"
				@click="navToBack"
				:src="xcxImgUrl && xcxImgUrl+'fanhui.svg'"
				style="width: 36rpx;height: 36rpx;"></image>
			<text :slot="'content'">活动购物车</text>
		</navBar>
		<!-- 编辑 -->
		<!-- #ifdef MP-WEIXIN -->
		<u-sticky offset-top="0">
			<!-- #endif -->
			<!-- #ifndef MP-WEIXIN -->
			<u-sticky offset-top="-44">
				<!-- #endif -->
				<view class="bianji pd_lr10">
					<view class="mian_confirmOrder_address_l mr10" @click="toAddress">
						<image src="@/static/newpic/cartAddress.svg"></image>
					</view>
				<view class="mian_confirmOrder_address_c mr10" >
						<text v-if="computedAddress" @click="toAddress">
					{{computedAddress}}
						</text>
						<text v-else>暂无收货地址</text>
				</view>
				<view @click="tapBianji"
					:style="{'color':switchShow ? '#ec4141' : '#333'}">
					{{switchShow ? '完成': '编辑' }}
				</view>
				</view>
			</u-sticky>
		<scroll-view scroll-y
			@scrolltolower="scrolltolower"
			:style="{'height': 'calc(100vh - ' + demoTopHieght +')'}"
			class="main_activeCard">
		

				<view v-for='(item,index) in computedisShelf(activceCardList)'
					:key="index"
					class="mian_allOrder_list_item pd_lr10">

					<view class="list_item_conter pd10" >
						<view class="list_item_conter_top">
							<view class="list_item_checked">
								<!-- <checkbox
								@click="selectChecked(index)"
								color="#ec4141"
								:checked="item.checked"
								style="transform:scale(0.7);border-radius: 50%;"></checkbox> -->
								<view class="custom_checkbox"
									:class="{active : item.checked[0]}">
									<u-checkbox-group v-model="item.checked"
										@change="selectChecked($event,index)">
										<u-checkbox :name="true"></u-checkbox>
									</u-checkbox-group>
								</view>
							</view>
							<view class="list_item_conter_top_img"
							@click="toDetails(item)"
								v-if="updateNoneImg"
								>
								<image :src="item.spuInfo && 
							 item.spuInfo.picture ? 
							 uploadImgUrl + item.spuInfo.picture :
							  computedMorentu"></image>
							</view>
							<view class="list_item_conter_top_text ml5" >
								<view class="list_item_conter_top_text_top texttowShow" @click="toDetails(item)">
									{{item.spuInfo &&
								item.spuInfo.name ? 
								item.spuInfo.name : ''}}
								</view>
								<view class="list_item_conter_top_text_bom ">
									<view class="list_item_conter_top_text_bom_item mt10">
										<text class="list_item_conter_top_text_bom_item_l">
											<text style="color: #ec4141;font-size: 28rpx;font-weight: bold;"
												class="mr10">￥{{item.price ? Utils.formatToFixed(item.price,'price') : 0}}
											</text>
										{{item.skuInfo && 
										item.skuInfo.specsOptionInfo && 
										item.skuInfo.specsOptionInfo.length && 
										item.skuInfo.unitInfo && 
										item.skuInfo.unitInfo.name ? 
										 item.skuInfo.specsOptionInfo.map(it=>it.optionName).join('-') + ' / ' + item.skuInfo.unitInfo.name :
										item.skuInfo.unitInfo.name }}
										</text>
										<view class="list_item_conter_top_text_bom_item_r"
											style="width:200rpx">
											<u-number-box>
												<view slot="minus"
													@click="delNum(item)"
													class="minus"
													:style="{background:item.qty <= 1 ? 'rgba(255, 0, 0, 0.5)' : ''}"
													>
													<u-icon name="minus"
														size="12"></u-icon>
												</view>
												<u-input border='none'
													style="width: 50px;text-align: center;"
													class="input"
													inputAlign='center'
													slot="input"
													type='number'
													v-model='item.qty'
													@blur='blurNum(item)'>
												</u-input>
												<!-- <text slot="input"
												style="width: 50px;text-align: center;"
												class="input"></text> -->
												<view slot="plus"
													@click="addNum(item)"
													class="plus">
													<u-icon name="plus"
														color="#FFFFFF"
														size="14"></u-icon>
												</view>
											</u-number-box>
										</view>
									</view>
									<view v-if="item.type == 2"
										class="biaoqian">
										优惠：{{item.preferential ? Utils.formatToFixed(item.preferential,'price') : 0}}元
									</view>
									<view v-if="item.type == 1"
										class="biaoqian">
										秒杀优惠
									</view>
								</view>
							</view>
						</view>
						<template v-if="item.type == 3 && item.children && item.children.length">
							<view v-for="(it,inx) in computedisShelf(item.children)"
								:key="inx"
								class="list_item_conter_bom mt10">
								<view class="list_item_conter_top_img" v-if="updateNoneImg">
									<image class="zenpin"
										:src="xcxImgUrl && xcxImgUrl+'zengpin.svg'"></image>
									<image :src="it.spuInfo && 
							 it.spuInfo.picture ? 
							 uploadImgUrl + it.spuInfo.picture :
							  computedMorentu"></image>
								</view>
								<view class="list_item_conter_top_text ml5">
									<view class="list_item_conter_top_text_top texttowShow">
										{{it.spuInfo && 
									 it.spuInfo.name ? 
									 it.spuInfo.name : ''}}
									</view>
									<view class="list_item_conter_top_text_bom ">
										<view class="list_item_conter_top_text_bom_item mt10">
											<text class="list_item_conter_top_text_bom_item_l">赠品：{{it.skuInfo && 
										it.skuInfo.specsOptionInfo && 
										it.skuInfo.specsOptionInfo.length && 
										it.skuInfo.unitInfo && 
										it.skuInfo.unitInfo.name ? 
										it.skuInfo.specsOptionInfo.map(it=>it.optionName).join('-') + '' + ' / ' + '' + it.skuInfo.unitInfo.name :
										it.skuInfo.unitInfo.name }} X{{it.num ? it.num : 0}}</text>
											<text class="list_item_conter_top_text_bom_item_r"> </text>
										</view>
									</view>
								</view>
							</view>
						</template>
					</view>

				</view>
				<view class="noShopping"
					v-if="activceCardList.length==0">
					<image style="width: 400rpx;height: 260rpx;"
						mode="aspectFill"
						:src="xcxImgUrl && xcxImgUrl+'shopping/kong_icon.svg'"></image>
					<text class="mt10">购物车无商品快去购买把！！</text>
				</view>
		</scroll-view>
		<!-- 合计结算 -->
		<view class="aggregateSettlement pd_left10">
			<view class="aggregateSettlement_checked">
				<!-- <checkbox 
					@click="selectAllChecked"
					:checked="allChecked"
					color="#ec4141"
					style="transform:scale(0.7);border-radius: 50%;"></checkbox> -->
				<view class="custom_checkbox"
					:class="{active : allChecked[0]}">
					<u-checkbox-group v-model="allChecked"
						@change="selectAllChecked">
						<u-checkbox :name="true"></u-checkbox>全选
					</u-checkbox-group>
				</view>
			</view>
			<view class="aggregateSettlement_right">
				<view v-if="!switchShow"
					class="aggregateSettlement_right_aggregate mr10">
					合计：
					<text>{{computedTotalMoney}}</text>
				</view>
				<view v-if="!switchShow"
					@click="tapQujiesuan"
					class="aggregateSettlement_right_settlement">
					结算
				</view>
				<view @click="delCommonity"
					style="background-color: black;"
					v-if="switchShow"
					class="aggregateSettlement_right_settlement">
					删除
				</view>
			</view>
		</view>

		<!-- 模态框确认 -->
		<u-modal :show="modalShow"
			:title="modalInfo.title"
			showConfirmButton
			showCancelButton
			@confirm='modalConfirm'
			@cancel='modalShow = false'
			:content='modalInfo.content'>

		</u-modal>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import {
		listMallShoppingCartPageInfo,
		updateMallShoppingCartCommodityQty,
		delMallShoppingCartCommodity
	} from '@/api/global.js'
	import {getDefaultMallCustomerAddress} from '@/api/setting.js'
	import {
		uploadImgUrl
	} from '@/utils/request.js'
	export default {
		computed: {
			...mapGetters(['demoTopHieght']),
			//返回默认图
			computedMorentu() {
				return this.$store.state.morentu
			},
			//返回有图无图控制
			updateNoneImg() {
				return this.$store.state.configSetting.noneImge == 1 ? false : true
			},
			computedisShelf() {
				return (item) => {
					return item.filter(v => v.skuInfo && v.skuInfo.skuInfo && v.skuInfo.skuInfo.shelfStatus == 2);
				}
			},
				computedAddress(){
										let province = this.addressInfo?.province || ''
										let city = this.addressInfo?.city || ''
										let area = this.addressInfo?.area || ''
										let address = this.addressInfo?.address || ''
										if(province == '' && city == '' && address == ''){
											return ''
										}else{
								        if(address)
									  { 
										  address = address.replace(/\n/g,'')
									   }}
									return province + city + area + address
										
			},
			//计算总计
			computedTotalMoney() {
				//满赠
				if (this.activeType == 1) {
					console.log(this.activceCardList)
					return this.activceCardList.filter(it => it.checked[0] == true).reduce((init, item) => {
						init += item.qty * item.price * 1;
						return this.Utils.formatToFixed(init, 'money') * 1;
					}, 0)
				}
				//满减
				if (this.activeType == 2) {
					//先计算出总的满减
					// let countPreferential = this.activceCardList.reduce((init,item)=>{
					// 	return init += item.preferential
					// },0)
					//在计算出总额
					return this.activceCardList.filter(it => it.checked[0] == true).reduce((init, item) => {
						init += this.Utils.formatToFixed((item.qty * item.price) - item.preferential, 'money') * 1
						return this.Utils.formatToFixed(init, 'money') * 1;
					}, 0)
				}
			}
		},
		data() {
			return {
				id:'',
				addressInfo:'',
				uploadImgUrl,
				statusBarHeight: '',
				hieght: '',
				value: 1,
				activceCardList: [], //购物车列表
				pageData: {
					currentPage: 1,
					pageSize: 10
				},
				lastPage: 0,
				activeType: '', //活动类型 1.满赠 2.满减
				activityId: '', //活动id
				allChecked: false, //全选
				switchShow: false, //false 编辑 true 完成
				modalShow: false, //模态框
				modalInfo: { //模态框提示对象内容
					title: '温馨提醒',
					content: ''
				}
			};
		},
		onLoad(options) {
			//接收活动类型 //活动类型 1.满赠 2.满减
			this.activeType = options?.activeType || ''
			this.activityId = options?.activityId || ''
			//获取购物车列表
			this.getActiveCardList()
			if(options?.address){
				//切换地址
				this.addressInfo = JSON.parse(options?.address) || ''
			}else{
				//获取默认收货地址
				this.getAddress()
			}
		},
		onShow() {
			this.$nextTick(() => {
				// 获取状态栏的高度
				this.statusBarHeight = this.$store.state.statusBarHeight * 2 + 'rpx'
				// 计算站位的高度
				this.hieght = (this.$store.state.navBarHeight) * 2 + 'rpx'
				//获取高度
				this.Utils.getDemoTopHeight('main_activeCard')
			})
		},
		methods: {
			toAddress(){
				uni.navigateTo({
				url:`/page_public/address?type=${this.type}`
				})},
			toDetails(item) {
				console.log(item);
				uni.navigateTo({
					url: `/page_public/commodityDetail?commodityId=${item.commodityId}`
				})
			},
			async getAddress(){
				let res = await getDefaultMallCustomerAddress()
				if(res.code == 2000){
					this.addressInfo = res?.data?.info || {}
				}else{
					this.Utils.toast(`${res.msg}`)
				}
			},
			//去结算
			tapQujiesuan() {
				//先筛选有没有选择 没有选择 提示先选择
				this.activceCardList = this.activceCardList.map(v => {
					if (v.children && v.children.length) {
						v.children = v.children.filter(a => a.skuInfo && a.skuInfo.skuInfo && a.skuInfo.skuInfo
							.shelfStatus == 2)
					}
					return v;
				})
				let arr = this.activceCardList.filter(it => it.checked[0] == true)
				console.log(arr)
				if (!arr.length) {
					this.Utils.toast(`请先选择需要结算的商品`)
					return
				}

				//先把购物车商品添加vuex =在结算页面回显
				this.$store.commit('cardCommonity', arr)
				//存储活动信息
				this.$store.commit('updateActivityInfo', {
					activityId: this.activityId,
					activeType: this.activeType
				})
				uni.navigateTo({
					url: `/page_public/confirmOrder?type=1&activityId=${this.activityId}&activeType=${this.activeType}&cartType=${this.activeType == 1 ? 3 : 2}&address=${JSON.stringify(this.addressInfo)}`
				})
			},
			//返回上一级
			navToBack() {
				// uni.navigateTo({
				// 	url:`/page_activity/activeDetails?activeType=${this.activeType}`
				// })
				uni.navigateBack()
			},
			//模态框确认
			async modalConfirm() {
				//关闭模态框
				this.modalShow = false
				let commodityDetailIdArr = []
				// 拿到筛选的商品commodityDetailId
				if (this.modalInfo.content === '当前数量只剩1件商品了，再减将会删除此商品，是否继续？？？') {
					commodityDetailIdArr = [this.id]
				} else{
					 commodityDetailIdArr = this.activceCardList.filter(it => it.checked[0] == true).map(it => it
						.commodityDetailId)
				}
					
				//获取类型 //类型[1：普通购物车 2：商品满减购物车 3：商品满赠购物车]
				let activeTypes = this.activeType == 1 ? 3 : this.activeType == 2 ? 2 : ''
				console.log(commodityDetailIdArr);
				let res = await delMallShoppingCartCommodity({
					type: activeTypes, //类型[1：普通购物车 2：商品满减购物车 3：商品满赠购物车]
					activityId: this.activityId,
					commodityDetailIds: commodityDetailIdArr
				})
				if (res.code == 2000) {
					this.Utils.toast('删除成功')
					this.pageData.currentPage = 1
					this.activceCardList = []
					this.getActiveCardList()

				} else {
					this.Utils.toast(`${res.msg}`)
				}
			},
			//点击删除商品
			delCommonity() {
				let checkedArr = this.activceCardList.filter(it => it.checked[0] == true)
				if (checkedArr.length <= 0) {
					this.Utils.toast(`请先选择商品`)
					return
				}
				this.modalShow = true
				this.modalInfo.content = '是否确定将要从购物车中将选中的所有商品删除？？？'

			},
			//点击编辑
			tapBianji() {
				this.switchShow = !this.switchShow
				//状态等于完成 取消全选状态
				// if (!this.switchShow) {
				// 	this.allChecked = false
				// }
			},
			//点击全选
			selectAllChecked(e) {
				this.allChecked = e;
				this.activceCardList.forEach(item => item.checked = this.allChecked)
			},
			//点击选择一个商品
			selectChecked(e, index) {
				//修改当前选择状态
				this.activceCardList[index].checked = e;
				//如果都选择 全选也选上
				if (this.activceCardList.every(item => item.checked[0] == true)) {
					this.allChecked = [true]
				} else {
					this.allChecked = [false]
				}
			},
			//点击加号添加数量
			addNum(item) {
				++item.qty
				this.updateCommonityQty(item)

			},
			//点击减号减少数量
			delNum(item) {
				
				if (item.qty <= 1) {
					item.qty = 1
					this.modalShow = true
					this.modalInfo.content = '当前数量只剩1件商品了，再减将会删除此商品，是否继续？？？'
					this.id = item.commodityDetailId		
				} else {
					--item.qty
					this.updateCommonityQty(item);
				}
				
			},
			//修改商品数量接口
			async updateCommonityQty(item) {
				//判断类型
				let activeTypes = this.activeType == 1 ? 3 : this.activeType == 2 ? 2 : ''
				let res = await updateMallShoppingCartCommodityQty({
					commodityDetailId: item.commodityDetailId || '', //商品SKUid
					qty: item.qty || 0,
					money: this.Utils.formatToFixed(item.qty * item.price, 'money') || 0,
					type: activeTypes, //类型[1：普通购物车 2：商品满减购物车 3：商品满赠购物车]
					activityId: item.activityId || '', //活动id

					// commodityId:item.commodityId || '',//商品SPUid
					// price:item?.defaultSKU?.skuPriceInfo?.[0]?.price || 0,
					// summary:'',
					// activityDetailId:item.detailId || '',//活动详情id
				})
				if (res.code == 2000) {
					this.getActiveCardList(item);
				} else {
					this.Utils.toast(`${res.msg}`);
				}
			},
			//数量输入框失去焦点
			blurNum(item) {
				if (item.qty * 1 > 10 ** 7) {
					item.qty = 10 ** 7;
				}
				item.qty = this.Utils.formatToFixed(item.qty * 1, 'number');
				console.log(item.qty)
				if (item.qty <= 1) {
					item.qty = 1
				}
				if (item.qty.toString().startsWith('0') && !item.qty.includes('.')) {
					item.qty = item.qty.slice(1, item.qty.length)
				}
				item.qty = parseInt(item.qty)
				this.updateCommonityQty(item)
			},

			//获取购物车列表
			async getActiveCardList(items) {
				let type = this.activeType == 1 ? 3 : this.activeType == 2 ? 2 : ''
				uni.showLoading()
				let res = await listMallShoppingCartPageInfo({
					type: type, //类型[1：普通购物车 2：商品满减购物车 3：商品满赠购物车]
					warehouseId: this.$store?.state?.warehouseInfo?.warehouseId || '', //仓库
					sort: 1,
					activityId: this.activityId || '', //活动id
					...this.pageData
				})
				if (res.code == 2000) {
					uni.hideLoading()
					if (this.pageData.currentPage == 1) {
						this.activceCardList = (res?.data?.info?.list || [])
					} else {
						this.activceCardList = this.activceCardList.concat(res?.data?.info?.list || [])
					}
					//循环添加字段
					this.activceCardList = this.activceCardList.map(item => {
						return {
							...item,
							checked: item && item.checked && item.checked[0] ? item.checked : [false]
						}
					})
					this.allChecked = [false];
					this.lastPage = res?.data?.info?.lastPage
				} else {
					this.Utils.toast(`${res.msg}`)
				}
			},
			//下拉加载
			scrolltolower() {
				
				if (this.pageData.currentPage >= this.lastPage) {
					return
				} else {
					this.pageData.currentPage++
					this.getActiveCardList()
				}
			}
		}
	}
</script>

<style lang="scss"
	scoped>
	/deep/.u-modal__button-group__wrapper--confirm.u-modal__button-group__wrapper--confirm  {
		background-color: #ec4141;
		
		.u-modal__button-group__wrapper__text {
			color: #FFF !important;
		}
	}
	 .mian_confirmOrder_address_c {
		  width: 300rpx;
		  white-space: nowrap; /* 防止文本换行 */
		  overflow: hidden;    /* 隐藏超出部分 */
		  text-overflow: ellipsis; /* 显示省略号 */
		   word-break: break-all;
		       margin-right: 250rpx;
			   
	  }
	.main_activeCard {
		width: 100%;
		box-sizing: border-box;
		background-color: #FFF;
		padding-bottom: 100rpx;

		.mian_allOrder_list_item {
			box-sizing: border-box;
			width: 100%;
			display: flex;
			align-items: center;
			border-bottom: 1px solid #f3f3f3;

			.list_item_checked {
				width: 40rpx;
				display: flex;
				align-items: center;
				margin-right: 20rpx;
				/deep/.u-icon__icon.uicon-checkbox-mark {
							font-weight: bold !important;
						}
			}

			.list_item_conter {
				flex: 1;
				border-bottom: 1px solid #f3f3f3;

				.list_item_conter_top,
				.list_item_conter_bom {
					display: flex;

					.list_item_conter_top_img {
						position: relative;
						border-radius: $border_radius_4;
						width: 120rpx;
						height: 120rpx;

						.zenpin {
							position: absolute;
							left: 0;
							top: 0;
							z-index: 999;
							width: 80rpx;
							height: 32rpx;
						}

						image {
							width: 100%;
							height: 100%;
						}
					}

					.list_item_conter_top_text {
						flex: 1;

						.list_item_conter_top_text_top {
							font-size: $font_size_12;
							color: $text_color_333;
						}

						.list_item_conter_top_text_bom {
							.list_item_conter_top_text_bom_item {
								font-size: $font_size_12;
								display: flex;
								justify-content: space-between;

								.list_item_conter_top_text_bom_item_l {
									padding-top: 20rpx;
									color: $text_color_808080;
									width: 280rpx;	
									white-space: nowrap; /* 防止文本换行 */
									overflow: hidden;    /* 隐藏超出部分 */
									text-overflow: ellipsis; /* 显示省略号 */
									.unit {
											font-size: $font_size_12;
											color: $text_color_808080;
											white-space: nowrap; /* 防止文本换行 */
											overflow: hidden;    /* 隐藏超出部分 */
											text-overflow: ellipsis; /* 显示省略号 */
											 // width: 100px;
																	}
								}

								.list_item_conter_top_text_bom_item_r {
									color: $text_color_333;
								}
							}

							.biaoqian {
								color: $text_color_ec4141;
								font-size: $font_size_12;
								padding: 4rpx 10rpx;
								background-color: #FFE3E3;
								width: 150rpx;
								text-align: center;
								border-radius: $border_radius_4;
							}

						}
					}
				}

				.list_item_conter_bom {
					margin-left: 100rpx;
				}
			}


		}
	}

	.bianji {
		width: 100%;
		font-size: $font_size_14;
		color: $text_color_333;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		// border: 1px solid red;
		background-color: #fff;
		padding: 10rpx 10rpx 10rpx 0;
		.mian_confirmOrder_address_l{
					width: 50rpx;
					height:50rpx;
					margin-left: 20rpx;
					image{
						width: 100%;
						height: 100%;
					}
	}}

	.aggregateSettlement {
		width: 100%;
		height: 88rpx;
		box-sizing: border-box;
		position: fixed;
		left: 0;
		bottom: 0;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
	  /deep/.u-icon__icon.uicon-checkbox-mark {
					font-weight: bold !important;
				}

		.aggregateSettlement_checked {
			font-size: $font_size_14;
			color: $text_color_333;
			margin-left: 16rpx;
		}

		.aggregateSettlement_right {
			display: flex;
			align-items: center;

			.aggregateSettlement_right_aggregate {
				font-size: $font_size_14;
				color: $text_color_333;

				text {
					color: $text_color_ec4141;
				}
			}

			.aggregateSettlement_right_settlement {
				width: 180rpx;
				height: 88rpx;
				background-color: $text_color_ec4141;
				color: #fff;
				font-size: 32rpx;
				font-weight: bold;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}

	// 计步器
	.minus {
		width: 22px;
		height: 22px;
		border-width: 1px;
		border-color: #E6E6E6;
		border-style: solid;
		border-top-left-radius: 100px;
		border-top-right-radius: 100px;
		border-bottom-left-radius: 100px;
		border-bottom-right-radius: 100px;
		background-color: rgba(255, 0, 0, 1);
		@include flex;
		justify-content: center;
		align-items: center;
		 /deep/.u-icon__icon.uicon-minus {
							font-weight: bold !important;
							color:#fff !important;
							font-size: 24rpx !important;
							
						}
	}

	.input {
		padding: 0 10px;
	}

	.plus {
		width: 22px;
		height: 22px;
		background-color: $text_color_ec4141;
		border-radius: 50%;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
		/deep/.u-icon__icon.uicon-plus{
									font-weight: bold !important;
									font-size: 24rpx !important;
									}
						
	}

	.noShopping {
		width: 100%;
		height: 660rpx;
		box-sizing: border-box;
		background-color: #fff;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: $font_size_12;
		color: $text_color_333;
	}
	/deep/.u-input {
			background-color: transparent !important;
			padding: 10px 10px !important;
		}
</style>